<template>
  <el-card style="height: 93%;">
    <div class="flex justify-center space-x-14 pt-10" v-if="isUpdate">
      <el-avatar shape="square" :size="200" :src="'api/uploads/' + userInfo.avatar" />
      <el-descriptions class="margin-top" title="个人信息" :column="4" direction="vertical" size="large" border>
        <template #extra>
          <el-button @click="handleUpdate()" type="primary" class=" bg-blue-500">编辑资料</el-button>
          <el-button @click="dialogVisible = true" type="success" class=" bg-green-600">绑定社保卡</el-button>
        </template>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <el-icon :style="iconStyle">
                <user />
              </el-icon>
              id
            </div>
          </template>
          {{ userInfo.id }}
        </el-descriptions-item>
        <el-descriptions-item width="150px">
          <template #label>
            <div class="cell-item">
              <el-icon :style="iconStyle">
                <user />
              </el-icon>
              用户名
            </div>
          </template>
          {{ userInfo.userName }}
        </el-descriptions-item>
        <el-descriptions-item width="150px">
          <template #label>
            <div class="cell-item">
              <el-icon :style="iconStyle">
                <user />
              </el-icon>
              昵称
            </div>
          </template>
          {{ userInfo.nickName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <el-icon :style="iconStyle">
                <iphone />
              </el-icon>
              邮箱
            </div>
          </template>
          {{ userInfo.email }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <el-icon :style="iconStyle">
                <tickets />
              </el-icon>
              注册日期
            </div>
          </template>
          {{ userInfo.createTime }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <el-icon :style="iconStyle">
                <iphone />
              </el-icon>
              性别
            </div>
          </template>
          {{ userInfo.sex == '1' ? '男' : "女" }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <el-icon :style="iconStyle">
                <location />
              </el-icon>
              用户类型
            </div>
          </template>
          {{ userInfo.userType == '1' ? "管理员" : "普通用户" }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <el-icon :style="iconStyle">
                <location />
              </el-icon>
              社保卡号
            </div>
          </template>
          {{ userInfo.securityNum }}
        </el-descriptions-item>
      </el-descriptions>
    </div>
    <div v-if="!isUpdate">
      <el-form class=" w-1/2 pl-60" ref="updateFormRef" :rules="rules" :model="userInfo" label-width="120px">
        <el-form-item>
          <el-upload :headers="headers" class="avatar-uploader" action="api/permission/upload" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input disabled v-model="userInfo.userName" />
        </el-form-item>
        <el-form-item label="注册日期">
          <el-input disabled v-model="userInfo.createTime" />
        </el-form-item>
        <el-form-item label="名称" prop="nickName">
          <el-input v-model="userInfo.nickName" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userInfo.email" />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="userInfo.sex" class="ml-4">
            <el-radio label="1" size="large">男</el-radio>
            <el-radio label="0" size="large">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-button @click="back()" size="large" class=" bg-blue-600 ml-28 w-32" type="primary">返回</el-button>
        <el-button @click="update(updateFormRef)" size="large" :loading="loading" class=" bg-blue-600 ml-28 w-32"
          type="primary">确定</el-button>
      </el-form>
    </div>
  </el-card>
  <el-dialog v-model="dialogVisible" title="绑定社保卡" width="40%" :before-close="handleClose">
    <el-form ref="ruleFormRef" :model="bindingData" :rules="bingdingRules" label-width="120px" class="demo-ruleForm"
      :size="formSize" status-icon>
      <el-form-item label="社保卡号" prop="securityNum">
        <el-input v-model="bindingData.securityNum" placehold="请输入社保卡号" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" class=" bg-blue-500" @click="handleBinding">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import store from '../../store/index.js'
import { updateUser, bindingNum, logout } from "../../api/modules";
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import router from "../../router/router";
const isUpdate = ref(true)
const loading = ref(false)
const updateFormRef = ref()
const dialogVisible = ref(false)
let userInfo = ref(JSON.parse(store.getters.UserInfo.UserInfo))
const bindingData = reactive({
  id: userInfo.value.id,
  securityNum: ''
})
const handleBinding = async () => {
  let res = await bindingNum(bindingData);
  if (res.data.data > 0) {
    ElNotification.success("绑定成功")
    let res = await logout()
    if (res.data.code == 200) {
      sessionStorage.removeItem("UserInfo")
      localStorage.removeItem("user")
      localStorage.removeItem("menu")
      localStorage.removeItem("token")
      setTimeout(() => {
        alert("信息发生变化，请重新登录")
        router.push("/login")
      }, 1000)
    } else {
      ElNotification.error(res.data.message)
    }
  }
  dialogVisible.value = false
  resetForm()
}
const handleCancel = () => {
  dialogVisible.value = false
  resetForm()
}
const validateNum = (rule, value, callback) => {
  if (value == "") {
    callback(new Error('社保卡号不能为空'))
  } else {
    //622908123124316898
    // let securityNumExp = /^(d{2})(d{2})(d{2})(d{8})(d{2})(d{1})([0-9a-zA-Z])$/
    // if (!securityNumExp.test(value)) {
    //   callback(new Error("社保卡号格式不正确"))
    // } else {
    callback()
    // }
  }
}
const bingdingRules = reactive({
  securityNum: [{ validator: validateNum, trigger: 'blur' }]
})
const handleClose = (done) => {
  ElMessageBox.confirm('您确定关闭对话框吗？')
    .then(() => {
      done()
      resetForm()
    })
    .catch(() => {
      // catch error
    })
}
const resetForm = () => {
  bindingData.securityNum = ''
}
const handleUpdate = () => {
  isUpdate.value = !isUpdate.value
}
const back = () => {
  userInfo.value = JSON.parse(store.getters.UserInfo.UserInfo)
  isUpdate.value = !isUpdate.value
}
const headers = { token: store.getters.token }
const validateEmail = (rule, value, callback) => {
  if (value == "") {
    callback(new Error('邮箱不能为空'))
  } else {
    let emailRegExp = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
    if (!emailRegExp.test(value)) {
      callback(new Error("邮箱格式不正确"))
    } else {
      callback()
    }
  }
}
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}
const rules = reactive({
  nickName: [{ required: true, message: '昵称不能为空', trigger: 'blur' },
  { min: 2, max: 10, message: '名称最少2个字符，不大于10个字符', trigger: 'blur' }],
  email: [{ validator: validateEmail, trigger: 'blur' },
  { min: 10, max: 20, message: '邮箱最少10个字符，不大于20个字符', trigger: 'blur' }]
})
const handleAvatarSuccess = (
  response,
  uploadFile
) => {
  imageUrl.value = "api/uploads/" + response.data
  userInfo.avatar = response.data
}

const imageUrl = ref('')
const update = (formEl) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      loading.value = true
      let res = await updateUser(userInfo.value);
      if (res.data.success == true) {
        ElMessage.success({
          message: '更新成功'
        })
        let res = await logout()
        if (res.data.code == 200) {
          sessionStorage.removeItem("UserInfo")
          localStorage.removeItem("user")
          localStorage.removeItem("menu")
          localStorage.removeItem("token")
          setTimeout(() => {
            alert("信息发生变化，请重新登录")
            router.push("/login")
            isUpdate.value = !isUpdate.value
          }, 1000)
        }
      }
    } else {
      console.log('error submit!')
      return false
    }
  })
}
</script>

<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
